package com.huangdebiao.oa.controller;

import com.alibaba.fastjson.JSON;
import com.huangdebiao.oa.entity.RoleEntity;
import com.huangdebiao.oa.service.RoleService;
import com.huangdebiao.oa.service.impl.RoleServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet(name = "HDB_RoleController",urlPatterns = "/HDBRole")
public class HDB_RoleController extends HDB_BaseController{

    private RoleService roleService = new RoleServiceImpl();

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String methodType = httpServletRequest.getMethod();

        if (methodType.equals("GET")){
            String method = servletRequest.getParameter("method");
            if (method.equals("findAllRole")){
                findAllRole(servletResponse);
            }
        }else if (methodType.equals("POST")){
            System.out.println(servletRequest);
            BufferedReader reader = servletRequest.getReader();
            String mapString = reader.readLine();
            Map<String,String> map = JSON.parseObject(mapString, HashMap.class);

            String method = map.get("method");
            if (method.equals("add")){
                String roleName = map.get("roleName");
                Integer integer = roleService.addRole(roleName);

                if (integer == 0){
                    printData(false,"",400,servletResponse);
                }else {
                    printData(true,"",200,servletResponse);
                }

            }


        }


//        if (method.equals("findAllRole")){
//            findAllRole(servletResponse);
//        }else if (method.equals("add")){
//            BufferedReader reader = servletRequest.getReader();
//            String roleName = reader.readLine();
//            roleService.addRole(roleName);
//            printData(true,"",200,servletResponse);
//        }



        //////////////////////////////////////////////





    }

    private void findAllRole(ServletResponse servletResponse) {
        List<RoleEntity> allRole = roleService.findAllRole();
        printData(true,allRole,200, servletResponse);
    }


}
